<?php
include_once('admin.inc.php');
$catModel = new Model('category');
$advModel = new Model('advertise');
$smarty = new Tpl();

$act = get_param('do');
switch( $act ){
	default:
	case 'categories':
		// 分类
		$catId = get_param('id');
		$where = "";
		if( $catId ){
			$where = "id=$catId";
		}
		$list = $catModel->where($where)->get();
		if( DEBUG ){
			echo $catModel->get_sql();
			dump($list);
		}

		// 广告图片
		$advList = $advModel->where('type=4')->get();
		$smarty->assign('advList',$advList);
		$smarty->assign('list',$list);
		$smarty->display('admin/categories.html');
	break;
	case 'addCat':
		if( is_uploaded_file($_FILES['advpic']['tmp_name']) ){
			$upCfg = array(
				// 文件大小：3M	
				'max_size'	=> 3*1024*1024,
				'safe_ext'	=> array('jpg','jpeg','png','gif','bmp','tiff'),
				'save_path'	=> __UPLOAD__.'advertise/'
				);
			$upSaveName = 'adv_4_';
			require_once(__LIB__.'Upload.class.php');
			$up = new Upload('advpic',$upCfg);
			$rsUp = $up->save($upSaveName);
			if( !$rsUp ){	
				msg('添加失败,文件上传失败,'.$up->get('error'),-1);
			}
		}
		$data = get_data();
		$data['edittime'] = time();
		unset($data['id']);
		if( empty($data['name']) ){
			msg('分类名称不能为空',-1);
		}
		$rsCat = $catModel->value($data)->add();
		if( $rsCat ){
			$rsUp = json_decode($rsUp, true);
			$dataAdv = array(
				'file' => $rsUp[0]['saveName'],
				'type' => 4,
				'link' => $data['link'],
				'subtitle' => $rsCat,
				);
			$advModel->value($dataAdv)->add();
		}else{
			msg('添加失败'.$catModel->get_sql(), 'category.php');
		}
		msg('添加成功','category.php');
		
	break;
	case 'editCat':
		$id = intval(get_param('id'));
		if( empty($id) ){
			msg('非法id',-1);
		}
		$data = get_data();
		if( is_uploaded_file($_FILES['advpic']['tmp_name']) ){
			$upCfg = array(
				// 文件大小：3M	
				'max_size'	=> 3*1024*1024,
				'safe_ext'	=> array('jpg','jpeg','png','gif','bmp','tiff'),
				'save_path'	=> __UPLOAD__.'advertise/'
			);
			$upSaveName = 'adv_4_';
			require_once(__LIB__.'Upload.class.php');
			$up = new Upload('advpic',$upCfg);
			$rsUp = $up->save($upSaveName);
			if( !$rsUp ){
				msg('修改失败,文件上传失败,'.$up->get('error'),-1);
			}
			$rsUp = json_decode($rsUp, true);
			$dataAdv = array(
				'file' => $rsUp[0]['saveName'],
				'type' => 4,
				'link' => $data['link'],
				'subtitle' => $id,
				);
			$advModel->value($dataAdv)->add();
		}

		$data['edittime'] = time();
		$rsCat = $catModel->where("id=$id")->value($data)->update();
		if( $rsCat ){
			msg('修改成功','category.php');
		}else{
			msg('修改失败');
		}
	break;
	case 'delCat':
		$id = intval(get_param('id'));
		if( empty($id) ){
			msg('非法id',-1);
		}
		$rs = $catModel->where("id=$id")->del();
		if( $rs ){
			ajax_return(array('status'=>'success','info'=>'删除成功'));
		}else{
			ajax_return(array('status'=>'failed','info'=>'删除失败'));
		}
		
	break;
}
